package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.heima.mapper.VmTypeMapper;
import com.heima.pojo.VmType;
import com.heima.pojo.dto.VmTypeDto;
import com.heima.pojo.vo.VmTypeVo;
import com.heima.service.VmTypeService;
import com.heima.utils.PageResult;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 赵超
 */
@Service
@RequiredArgsConstructor
public class VmTypeServiceImpl extends ServiceImpl<VmTypeMapper, VmType> implements VmTypeService {
    private final VmTypeMapper vmTypeMapper;

    @Override
    public PageResult<VmTypeVo> page(String name, Integer pageIndex, Integer pageSize) {
        //使用mybatis plus分页插件查询
        Page<VmType> mpPage = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<VmType> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtil.isEmpty(name)) {
            queryWrapper.like(VmType::getName, name);
        }
        IPage<VmType> result = vmTypeMapper.selectPage(mpPage, queryWrapper);

        //转换
        List<VmTypeVo> list = result.getRecords().stream().map(vmType -> {
            VmTypeVo vo = new VmTypeVo();
            BeanUtils.copyProperties(vmType, vo);
            return vo;
        }).toList();

        int totalPage = (int) result.getPages();
        long totalCount = result.getTotal();

        return new PageResult<>(pageIndex, pageSize, totalPage, totalCount, list);
    }

    @Override
    public int add(VmTypeDto vmTypeDto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(vmTypeDto, vmType);
        return vmTypeMapper.insert(vmType);
    }

    @Override
    public int update(Integer typeId, VmTypeDto vmTypeDto) {
        VmType vmType = new VmType();
        BeanUtils.copyProperties(vmTypeDto, vmType);
        vmType.setTypeId(typeId);
        return vmTypeMapper.updateById(vmType);
    }

    @Override
    public int delete(Integer typeId) {
        return vmTypeMapper.deleteById(typeId);
    }
}
